package org.coast.mvc.logging;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 1. logRecord 每打印一条log的记录
 * 2. LogHandler的实现 console file socket db
 * 3. Format log的格式
 * 4. LogLevel log的级别
 */
public class Logger {

    private static final Map<String, Logger> loggerMap = new HashMap<>();

    //log name
    private String name;

    private LogLevel logLevel;

    //log 对应的处理器
    private List<LogHandler> logHandlerList = new ArrayList<>();

    private Logger(String name) {
        this.name = name;
        try {
            LoggerHelper loggerHelper = LoggerHelper.getLoggerHelper();
            Logger logger = loggerHelper.deduceLogger(name);
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    private void configHandlerList(String name) {

    }

    //双检锁检查缓存
    public static Logger getLogger(String name) {
        Logger logger = loggerMap.get(name);
        if (Objects.isNull(logger)) {
            synchronized (loggerMap) {
                if (loggerMap.get(name) == null) {
                    logger = new Logger(name);
                    loggerMap.put(name, logger);
                }
            }
        }

        return logger;
    }

    public void info(String msg) {
        String type = System.getProperty(LogConstants.LOG_TYPE);
        List<LogHandler> logHandlers = logHandlerList.stream().filter(item -> item.accept(type)).collect(Collectors.toList());
        for (LogHandler logHandler : logHandlers) {
            logHandler.publish(new LogRecord(msg));
        }
    }

    public static void main(String[] args) {
        System.setProperty(LogConstants.LOG_TYPE, "console");
        System.setProperty(LogConstants.LOG_LEVEL, "DEBUG");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<LogHandler> getLogHandlerList() {
        return logHandlerList;
    }

    public void setLogHandlerList(List<LogHandler> logHandlerList) {
        this.logHandlerList = logHandlerList;
    }
}
